<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目管理演示</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 20px;
            background-color: #f5f7fa;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .login-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .login-form {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .login-form input, .login-form button {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .login-form button {
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        
        .login-form button:hover {
            background: #0056b3;
        }
        
        .status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }
        
        .status.success {
            background: #d4edda;
            color: #155724;
        }
        
        .status.error {
            background: #f8d7da;
            color: #721c24;
        }
        
        .test-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .test-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        
        .test-buttons button {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn-primary { background: #007bff; color: white; }
        .btn-success { background: #28a745; color: white; }
        .btn-warning { background: #ffc107; color: #212529; }
        .btn-danger { background: #dc3545; color: white; }
        
        .result {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            border-left: 4px solid #007bff;
            margin-top: 15px;
        }
        
        .result pre {
            margin: 0;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        
        .iframe-container {
            margin-top: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .iframe-container iframe {
            width: 100%;
            height: 600px;
            border: none;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🚀 项目管理功能演示</h1>
        <p>测试项目管理的查看、创建、编辑和删除功能</p>
    </div>

    <!-- 登录区域 -->
    <div class="login-section">
        <h3>🔐 登录测试</h3>
        <div class="login-form">
            <input type="text" id="username" placeholder="用户名" value="sbxnh">
            <input type="password" id="password" placeholder="密码" value="123456">
            <button onclick="login()">登录</button>
            <button onclick="checkLoginStatus()">检查登录状态</button>
        </div>
        <div id="loginStatus"></div>
    </div>

    <!-- API测试区域 -->
    <div class="test-section">
        <h3>🔧 API功能测试</h3>
        <div class="test-buttons">
            <button class="btn-primary" onclick="testGetProjects()">获取项目列表</button>
            <button class="btn-primary" onclick="testGetUsers()">获取用户列表</button>
            <button class="btn-success" onclick="testCreateProject()">创建测试项目</button>
            <button class="btn-warning" onclick="testUpdateProject()">更新项目</button>
            <button class="btn-danger" onclick="testDeleteProject()">删除项目</button>
        </div>
        <div id="testResult"></div>
    </div>

    <!-- 完整项目管理界面 -->
    <div class="test-section">
        <h3>📊 完整项目管理界面</h3>
        <p>下面是完整的项目管理界面，包含所有功能：</p>
        <div class="iframe-container">
            <iframe src="project-management.html"></iframe>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8080';
        let token = '';

        // 登录功能
        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const statusDiv = document.getElementById('loginStatus');

            try {
                const response = await fetch(`${API_BASE}/auth/login`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, password })
                });

                if (response.ok) {
                    const data = await response.json();
                    token = data.token;
                    localStorage.setItem('token', token);
                    statusDiv.innerHTML = '<div class="status success">✅ 登录成功！</div>';
                } else {
                    statusDiv.innerHTML = '<div class="status error">❌ 登录失败</div>';
                }
            } catch (error) {
                statusDiv.innerHTML = '<div class="status error">❌ 网络错误</div>';
            }
        }

        // 检查登录状态
        function checkLoginStatus() {
            const savedToken = localStorage.getItem('token');
            const statusDiv = document.getElementById('loginStatus');
            
            if (savedToken) {
                token = savedToken;
                statusDiv.innerHTML = '<div class="status success">✅ 已登录</div>';
            } else {
                statusDiv.innerHTML = '<div class="status error">❌ 未登录</div>';
            }
        }

        // 通用API请求
        async function apiRequest(endpoint, options = {}) {
            if (!token) {
                token = localStorage.getItem('token');
                if (!token) {
                    throw new Error('请先登录');
                }
            }

            const response = await fetch(`${API_BASE}${endpoint}`, {
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                    ...options.headers
                },
                ...options
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText}`);
            }

            return await response.json();
        }

        // 显示测试结果
        function showResult(title, data) {
            const resultDiv = document.getElementById('testResult');
            resultDiv.innerHTML = `
                <div class="result">
                    <h4>${title}</h4>
                    <pre>${JSON.stringify(data, null, 2)}</pre>
                </div>
            `;
        }

        // 显示错误
        function showError(title, error) {
            const resultDiv = document.getElementById('testResult');
            resultDiv.innerHTML = `
                <div class="result" style="border-left-color: #dc3545;">
                    <h4 style="color: #dc3545;">${title}</h4>
                    <pre style="color: #dc3545;">${error.message}</pre>
                </div>
            `;
        }

        // 测试获取项目列表
        async function testGetProjects() {
            try {
                const projects = await apiRequest('/projects');
                showResult('📋 项目列表', projects);
            } catch (error) {
                showError('获取项目列表失败', error);
            }
        }

        // 测试获取用户列表
        async function testGetUsers() {
            try {
                const users = await apiRequest('/users');
                showResult('👥 用户列表', users);
            } catch (error) {
                showError('获取用户列表失败', error);
            }
        }

        // 测试创建项目
        async function testCreateProject() {
            try {
                // 先获取用户列表以获取负责人ID
                const users = await apiRequest('/users');
                if (users.length === 0) {
                    throw new Error('没有可用的用户作为项目负责人');
                }

                const projectData = {
                    projectName: '测试项目 ' + new Date().getTime(),
                    projectCode: 'TEST' + new Date().getTime(),
                    description: '这是一个通过API创建的测试项目',
                    startDate: '2025-07-01',
                    endDate: '2025-12-31',
                    status: 'IN_PROGRESS',
                    budgetAmount: 100000.00,
                    principalInvestigatorId: users[0].id
                };

                const newProject = await apiRequest('/projects', {
                    method: 'POST',
                    body: JSON.stringify(projectData)
                });

                showResult('✅ 项目创建成功', newProject);
            } catch (error) {
                showError('创建项目失败', error);
            }
        }

        // 测试更新项目
        async function testUpdateProject() {
            try {
                // 先获取项目列表
                const projects = await apiRequest('/projects');
                if (projects.length === 0) {
                    throw new Error('没有可更新的项目，请先创建项目');
                }

                const projectToUpdate = projects[0];
                const users = await apiRequest('/users');

                const updateData = {
                    projectName: projectToUpdate.projectName + ' (已更新)',
                    projectCode: projectToUpdate.projectCode,
                    description: '项目描述已更新 - ' + new Date().toLocaleString(),
                    startDate: projectToUpdate.startDate,
                    endDate: projectToUpdate.endDate,
                    status: 'IN_PROGRESS',
                    budgetAmount: 150000.00,
                    principalInvestigatorId: users[0].id
                };

                const updatedProject = await apiRequest(`/projects/${projectToUpdate.id}`, {
                    method: 'PUT',
                    body: JSON.stringify(updateData)
                });

                showResult('✅ 项目更新成功', updatedProject);
            } catch (error) {
                showError('更新项目失败', error);
            }
        }

        // 测试删除项目
        async function testDeleteProject() {
            if (!confirm('确定要删除一个测试项目吗？')) {
                return;
            }

            try {
                // 先获取项目列表
                const projects = await apiRequest('/projects');
                if (projects.length === 0) {
                    throw new Error('没有可删除的项目');
                }

                // 找到测试项目（名称包含"测试"的项目）
                const testProject = projects.find(p => p.projectName && p.projectName.includes('测试'));
                if (!testProject) {
                    throw new Error('没有找到测试项目');
                }

                const result = await apiRequest(`/projects/${testProject.id}`, {
                    method: 'DELETE'
                });

                showResult('✅ 项目删除成功', { 
                    message: '项目删除成功',
                    deletedProject: testProject
                });
            } catch (error) {
                showError('删除项目失败', error);
            }
        }

        // 页面加载时检查登录状态
        window.onload = function() {
            checkLoginStatus();
        };
    </script>
</body>
</html>
